package com.think.archive.service.impl;

import com.think.archive.dto.SysUserDto;
import com.think.archive.mapper.SysRoleMapper;
import com.think.archive.mapper.SysUserMapper;
import com.think.archive.model.SysRole;
import com.think.archive.model.SysUser;
import com.think.archive.model.SysUserExample;
import com.think.archive.service.SysUserService;
import ma.glasnost.orika.MapperFactory;
import ma.glasnost.orika.impl.DefaultMapperFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class SysUserServiceImpl implements SysUserService {

    @Autowired
    SysUserMapper userMapper;

    @Autowired
    SysRoleMapper roleMapper;

    @Override
    public List<SysUserDto> selectAllUser() {
        SysUserExample userExample=new SysUserExample();
        SysUserExample.Criteria criteria=userExample.createCriteria();
        List<SysUser> users=userMapper.selectByExample(userExample);
        List<SysUserDto> userDtos=transUserToDtos(users);
//        criteria.andStatusEqualTo(1);
        return userDtos;
    }

    @Override
    public int insertOrUpdateUser(SysUser user) {
        if(user.getId()==null||user.getId()==0){
            user.setCreateTime(new Date());
            return userMapper.insert(user);
        }
        else{
            SysUser userSave=userMapper.selectByPrimaryKey(user.getId());
            userSave.setUsername(user.getUsername());
            userSave.setRealname(user.getRealname());
            userSave.setRoleCode(user.getRoleCode());
            userSave.setStatus(user.getStatus());
            userSave.setTelephone(user.getTelephone());
            userMapper.updateByPrimaryKey(userSave);
            return userSave.getId();
        }
    }

    @Override
    public int deleteUser(int id) {
        return userMapper.deleteByPrimaryKey(id);
    }

    @Override
    public int changeStatusUser(int id, String status) {
        SysUser user=userMapper.selectByPrimaryKey(id);
        user.setStatus(status);
        return userMapper.updateByPrimaryKey(user);
    }

    @Override
    public SysUserDto transUserToDto(SysUser user){
        MapperFactory mapperFactory = new DefaultMapperFactory.Builder().build();
        SysUserDto userDto = mapperFactory.getMapperFacade().map(user, SysUserDto.class);
        SysRole role=roleMapper.selectByCode(user.getRoleCode());
        if(role!=null){
            userDto.setRoleName(role.getRoleName());
        }
        else{
            userDto.setRoleName("/");
        }
        return userDto;
    }

    @Override
    public List<SysUserDto> transUserToDtos(List<SysUser> users){
        List<SysUserDto> userDtos=new ArrayList<>();
        for(SysUser user:users){
            SysUserDto userDto=transUserToDto(user);
            userDtos.add(userDto);
        }
        return userDtos;
    }
}
